package com.company.linkedlist;

public class Josephu {
    public static void main(String[] args) {
        CricleSingleLinkedList csll=new CricleSingleLinkedList();
        csll.addBoy(25);
        csll.showBoy();
        csll.countBoy(1,2,25);
    }
}

class CricleSingleLinkedList{
    private Boy first = null;

    public void addBoy(int n){
        if (n<1){
            System.out.println("nums的值不正确");
            return;
        }
        Boy curBoy = null;
        for (int i = 0; i < n; i++) {
            Boy boy=new Boy(i+1);
            if (i==0){
                first=boy;
                first.setNext(first);
                curBoy=first;
            }else{
                curBoy.setNext(boy);
                boy.setNext(first);
                curBoy=boy;
            }
        }
    }

    public void showBoy(){
        if (first==null){
            System.out.println("没有任何小孩~~");
            return;
        }
        Boy curBoy=first;
        while (true){
            System.out.println("小孩的编号："+curBoy.getNo());
            curBoy=curBoy.getNext();
            if (curBoy==first){
                break;
            }
        }
    }

    public void countBoy(int startNo, int countNum,int nums){

        if (first == null || startNo < 1 || startNo>nums){
            System.out.println("参数输入有误，请重新输入");
            return;
        }
        Boy helper = first;
        while (true){
            if (helper.getNext()==first){
                break;
            }
            helper=helper.getNext();
        }
        for (int j=0;j<startNo-1;j++){
            first=first.getNext();
            helper=helper.getNext();
        }
        while(true){
            if (helper==first){
                break;
            }
            for (int j=0;j<countNum-1;j++){
                first=first.getNext();
                helper=helper.getNext();
            }
            System.out.println("小孩"+first.getNo()+"出圈");
            first=first.getNext();
            helper.setNext(first);
        }
        System.out.println("最后留在圈中的小孩编号"+helper.getNo());
    }
}

class Boy{
    private int no;
    private Boy next;

    public Boy(int no){
        this.no=no;
    }
    public int getNo(){
        return no;
    }

    public Boy getNext() {
        return next;
    }

    public void setNext(Boy boy){
        this.next=boy;
    }
}


